//
//  ViewController.m
//  TaoBao购物车动画
//
//  Created by Guo Rui on 2017/10/27.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) UIView *greenView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(40.f, 80.f, width - 2 * 40, height - 2 * 80)];
    greenView.backgroundColor = [UIColor greenColor];
    [self.view addSubview:greenView];
    self.greenView = greenView;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [UIView animateKeyframesWithDuration:.5 delay:0.0 options:0 animations:^{
            [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.35 animations:^{
                self.greenView.layer.transform = [self stepOneTransform];
            }];
            [UIView addKeyframeWithRelativeStartTime:0.35 relativeDuration:0.65 animations:^{
                self.greenView.layer.transform = [self stepTwoTransformWithView:self.greenView];
            }];
        
         } completion:nil];

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [UIView animateKeyframesWithDuration:.5 delay:0 options:0 animations:^{
       
        [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.35 animations:^{
            self.greenView.layer.transform = [self stepOneTransform];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.35 relativeDuration:0.65 animations:^{
            self.greenView.layer.transform = CATransform3DIdentity;
        }];
        
    } completion:^(BOOL finished) {
        
    }];
}


- (CATransform3D)stepOneTransform{
    CGFloat stepOneScale = 0.9;
    CGFloat rotationRatio = 1 + (0.95 - stepOneScale) * 3.0f;
    CATransform3D t1 = CATransform3DIdentity;
    t1.m34 = 1.0 / -900;
    t1 = CATransform3DScale(t1, stepOneScale, stepOneScale, 1);
    t1 = CATransform3DRotate(t1, 15.0f * M_PI / 180.0f * rotationRatio * -1, 1, 0, 0);
    return t1;
}

- (CATransform3D)stepTwoTransformWithView:(UIView*)view{
    CATransform3D t2 = CATransform3DIdentity;
    t2.m34 = [self stepOneTransform].m34;
    CGFloat x = 0;
    CGFloat y = -view.frame.size.height * 0.08 ;
    t2 = CATransform3DTranslate(t2, x, y, 0);
    
    CGFloat stepTwoScale = 0.8;
    t2 = CATransform3DScale(t2, stepTwoScale, stepTwoScale, 1);
    
    return t2;
}
@end
